package day20;

import java.io.*;
import java.net.Socket;

//处理客户端请求----处理请求并响应----拦截器
public class ClientHandler {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            File file = new File("./index.html");//创建一个文件对象
            OutputStream output = socket.getOutputStream();//获取输出流
            String data = "HTTP/1.1 200 OK\r\n" +//响应头
                    "Content-Type: text/html\r\n" +//响应头
                    "Content-Length: " + file.length() + "\r\n" + "\r\n";//响应头
            output.write(data.getBytes());//响应头
            InputStream input = new FileInputStream(file);//创建一个文件输入流
            int d = 0;//存储读取的字节
            while ((d = input.read()) != -1) {//读取文件内容
                output.write(d);//响应文件内容
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //1.接收客户端请求
        //2.处理客户端请求
        //3.响应客户端请求
        try {
            while (true) {
                String line = readLine();
                if ((line.isEmpty())) {
                    break;
                }
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String readLine() throws IOException {
        InputStream input = socket.getInputStream();
        int d = 0;//读取的字节
        char cur = 'a';//当前读取的内容
        char per = 'a';//上次读取到的内容
        StringBuilder builder = new StringBuilder();//存储读取到的内容创建了一个StringBuilder
        while ((d = input.read()) != -1) {
            cur = (char) d;//将读取到的内容转换为字符
            if (cur == 13 && per == 10) {//读取到回车换行符
                break;//跳出循环
            }
            builder.append(cur);//将读取到的内容添加到builder中  拼接
            per = cur;//将当前读取到的内容赋值给per 继续下次循环
        }
        String line = builder.toString().trim();
        return line;
    }
}
